<template>
    <div class="sys-page">
        <!-- <app-title :title="dialogTitle" style="display:inline;"></app-title> -->
        <el-button type="success" size="mini" @click="refresh()" round style="margin-top:10px;margin-bottom:10px;" icon="el-icon-refresh">刷新</el-button>
        <el-button type="info" size="mini" @click="download()" round style="margin-top:10px;margin-bottom:10px;" icon="el-icon-download">导出</el-button>
         <!-- <el-button type="success" @click="refresh()" circle style="float:right; margin-top:10px;" icon="el-icon-refresh">刷新</el-button>
 -->        <!-- <app-notes><el-button @click="searchFlag = true">操作日志报表统计分析</el-button></app-notes> -->
        <el-collapse  accordion>
              <el-collapse-item >
                <template slot="title">
                  <span style="font-size:20px;color:orange;">统计分析</span><i class="header-icon el-icon-search"></i>
                </template>

                <el-form :model="form" :label-width="formLabelWidth">
                <el-row>
                    <el-col :span="6">
                        <el-form-item label="用户" >
                            <el-input v-model="form.userId" auto-complete="off"></el-input>
                        </el-form-item>
                    </el-col>
                    <el-col :span="6">
                        <el-form-item label="来源"  :label-width="formLabelWidth" >
                            <el-input v-model="form.source" auto-complete="off"></el-input>
                        </el-form-item>
                    </el-col>
                    
                    <el-col :span="6">
                        <el-form-item label="模块" :label-width="formLabelWidth">
                            <el-select v-model="form.module" placeholder="请选择模块类型">
                                <el-option label="系统管理" value="A"></el-option>
                                <el-option label="安全管理" value="B"></el-option>
                                <el-option label="业务办理" value="C"></el-option>
                                <el-option label="审计管理" value="D"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    
                    <el-col :span="6">
                        <el-form-item label="结果" :label-width="formLabelWidth">
                            <el-select v-model="form.result" placeholder="请选择活动区域">
                                <el-option label="成功" value="0"></el-option>
                                <el-option label="失败" value="1"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>

                <el-row>
                    <el-col :span="7">
                        <el-form-item label="起始时间" :label-width="formLabelWidth">
                            <el-date-picker type="datetime" placeholder="选择时间" v-model="form.stime" @change="getSTime"  value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;"></el-date-picker>

                        </el-form-item>
                    </el-col>
                    <el-col :span="7">
                        <el-form-item label="结束时间" :label-width="formLabelWidth">
                            <el-date-picker type="datetime" placeholder="选择时间" v-model="form.etime" @change="getETime" value-format="yyyy-MM-dd HH:mm:ss" style="width: 100%;"></el-date-picker>

                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
                 <el-button icon="el-icon-delete" @click="reset">重置</el-button>
                <el-button icon="el-icon-search" type="primary" @click="conditionQuery">确 定</el-button>
            </el-collapse-item>
        </el-collapse>

            <el-table v-loading="loading" :data="tableData.body" >
                <el-table-column type="expand">
                  <template slot-scope="props">
                    <el-form label-position="left" inline class="demo-table-expand">
                      <el-form-item label="操作时间" >
                        <span>{{ timeFormatter(props.row, null, null) }}</span>
                      </el-form-item>
                      <el-form-item label="触发用户">
                        <span>{{ props.row.userId }}</span>
                      </el-form-item>
                      <el-form-item label="事件">
                        <span>{{ eventFormatter(props.row, null, null) }}</span>
                      </el-form-item>
                      <el-form-item label="终端IP">
                        <span>{{ props.row.source }}</span>
                      </el-form-item>
                      <el-form-item label="类型">
                        <span>{{ typeFormatter(props.row, null, null) }}</span>
                      </el-form-item>
                      <el-form-item label="所属模块">
                        <span>{{ moduleFormatter(props.row, null, null) }}</span>
                      </el-form-item>
                      <el-form-item label="结果">
                        <span>{{ resultFormatter(props.row, null, null) }}</span>
                      </el-form-item>
                      <el-form-item label="描述" style="margin-right: 0; margin-bottom: 0; width:100%;">
                        <span style="color:red;">{{ props.row.desc }}</span>
                      </el-form-item>
                    </el-form>
                  </template>
                </el-table-column>

                <el-table-column style="background-color:16#123456" label="数据安全" width="120" align="center">
                    

                   <template slot-scope="scope">
                        <div v-if="scope.row.safe==false">
                            <i class="el-icon-warning"></i>
                            <span style="color:red"> 数据异常</span>
                        </div>
                        <div v-else-if="scope.row.safe==true">
                            <i class="el-icon-success"></i>
                            <span style="color:green">数据完整</span>
                        </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作时间" align="center" width="170" prop="time" :formatter="timeFormatter">
                </el-table-column>
                <el-table-column label="用户" align="center" width="100" prop="userId"></el-table-column>
                <el-table-column label="来源"  align="center" width="140" prop="source"></el-table-column>
                <el-table-column label="事件"  align="center" width="180" prop="event" :formatter="eventFormatter"></el-table-column>
                <el-table-column label="类型"  align="center" width="80" prop="type" :formatter="typeFormatter"></el-table-column>
                <el-table-column label="模块" align="center"  width="100" prop="module" :formatter="moduleFormatter"></el-table-column>
                <el-table-column label="结果" align="center"   prop="result" :formatter="resultFormatter"></el-table-column>
                <!-- <el-table-column label="描述"  align="center" width="220" prop="desc"></el-table-column> -->
                 
            </el-table>
            <div align="center">
              <el-pagination
                  @size-change="handleSizeChange"
                  @current-change="handleCurrentChange"
                  :current-page="currentPage"
                  :page-sizes="[10, 20, 30, 40]"
                  :page-size="pageSize"
                  layout="total, sizes, prev, pager, next, jumper"
                  :total="totalCount">
              </el-pagination>
          </div>

         <div class="sys-page">
            <app-section title="操作日志报表统计">
               <!--  <app-toolbar>
                    <el-button type="primary" @click="getChartData">刷新数据</el-button>
                </app-toolbar> -->
                <div style="display:inline; float:left" id="myChart" :style="{width: '600px', height: '500px'}"></div>
                <div style="display:inline; float:left" id="myBar" :style="{width: '600px', height: '500px'}"></div>
            </app-section>
        </div>
    </div>
</template>
<style>
  .el-table .warning-row {
    background: #F08080;
  }

  .el-table .success-row {
    background:#f0f9eb;
  }

  .demo-table-expand {
    font-size: 0;
  }
  .demo-table-expand label {
    width: 130px;
    color: #99a9bf;
  }
  .demo-table-expand .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 33%;
  }
</style>

<script>
import mEcharts from 'echarts'

export default {
    name: 'operlog',
    data(){
        return {
            dialogTitle:"用户操作日志查询",
            loading: false,
            searchFlag: false,
            pageNum: 1,
            dataCount: null,
            totalCount: 1000,
            pageSize: 10,
            currentPage: 1,
            start: 1,
            url: window.axios_g.BASEURL,
            reportPermission: false,
            echartList:[],
            categoryKeyList:[],
            categoryValueList:[],
            echartList2:[],
            tableData:{
                body:[],
                head:[],
                loading : true
            },
            exportCondition: {
                result: null,
                userId: null,
                module: null,
                source: null,
                stime: null,
                etime: null
            },
            form: {
                result: null,
                userId: null,
                module: null,
                source: null,
                stime: null,
                etime: null
            },
            formLabelWidth: '120px',
            errorMsg:"您的信息有误，请联系管理员修改",
            reliable:true,

       }
    },
    mounted(){
        this.initPermissionMap()
        this.query()
        this.exportCondition.result=null
        this.exportCondition.userId=null
        this.exportCondition.module=null
        this.exportCondition.source=null
        this.exportCondition.stime=null
        this.exportCondition.etime=null

    },
    methods:{
        showReport(){
             let msg = {
            result: this.form.result,
            event: this.form.event,
            source:this.form.source,
            userId: this.form.userId,
            group: 'user_id',
            stime: this.timeStrToTimestamp(this.form.stime),
            etime: this.timeStrToTimestamp(this.form.etime)
          }
          let msg2 = {
            result: this.form.result,
            event: this.form.event,
            source:this.form.source,
            userId: this.form.userId,
            group: 'module',
            stime: this.timeStrToTimestamp(this.form.stime),
            etime: this.timeStrToTimestamp(this.form.etime)
          }
            let url = "/opera-logger/report.shtml?entity="+encodeURI(JSON.stringify(msg));
            let url2 = "/opera-logger/report.shtml?entity="+encodeURI(JSON.stringify(msg2));
            this.HTTP.methods.apiGet(url).then(res =>
            {
                if(res.code == 200){
                    if(res.data){
                        console.log(res)
                        this.echartList = []
                        for(let i=0; i<res.data.length; i++){
                            let obj = {value:res.data[i].count,
                                    name: res.data[i].group}
                            this.echartList.push(obj)
                        }
                    }
                    this.drawPie('myChart')
                }
            })
            this.HTTP.methods.apiGet(url2).then(res =>
            {
                if(res.code == 200){
                    if(res.data){
                        console.log(res)
                        this.categoryKeyList = []
                        this.categoryValueList = []
                        for(let i=0; i<res.data.length; i++){
                            if(res.data[i].group == 'A'){
                            this.categoryKeyList.push('系统管理')
                            }else if(res.data[i].group=='B'){
                            this.categoryKeyList.push('安全管理')
                            }else if(res.data[i].group=='C'){
                                this.categoryKeyList.push('业务办理')
                            }else if(res.data[i].group=='D'){
                                this.categoryKeyList.push('审计管理')
                            }else if(res.data[i].group=='X'){
                                this.categoryKeyList.push('基础模块')
                            }
                            
                             this.categoryValueList.push(res.data[i].count)
                            // let obj = {value:res.data[i].count,
                            //         name: res.data[i].group}
                            // this.echartList2.push(obj)
                        }
                    }
                    this.drawTable('myBar')
                }
            })
        },
        drawTable(obj){
            /*ECharts图表*/
         let myChart = mEcharts.init(document.getElementById(obj));
         myChart.setOption(
            {
            title: {
                text: '各个模块的操作次数统计',
                left: 'center',
                top: 20
            },
            color: ['#3398DB'],
            tooltip : {
                 
            },
            toolbox: {
                show : true,
                feature : {
                    dataView : {show: true, readOnly: false},
                    magicType : {show: true, type: ['line', 'bar']},
                    restore : {show: true},
                    saveAsImage : {show: true}
                }
            },
            grid: {
                left: '3%',
                right: '4%',
                y2:80,
                containLabel: true
            },
            xAxis : [
                {
                    type : 'category',
                    data : this.categoryKeyList,  //重点在这里  加载后台数据  横坐标名称
                    axisTick: {
                        alignWithLabel: true
                    },
                    axisLabel:{
                        interval:0,
                        rotate:-30
                    }
                }
                 
            ],
            yAxis : [
                {
                    type : 'value'
                }
            ],
            series : [
                {
                    name:'留痕登记数',
                    type:'bar',
                    barWidth: '60%',
                    data: this.categoryValueList  //重点在这里   加载数据  柱状图数据
                }
            ]
        }
        )
        },
        drawPie(obj){
            /*ECharts图表*/
         var myChart = mEcharts.init(document.getElementById(obj));
         myChart.setOption({
          series : [
           {
            name: '用户登陆频率统计',
            type: 'pie',
            radius: '50%',
            itemStyle:{ 
              normal:{ 
                    label:{ 
                      show: true, 
                      formatter: '{b} : {c} ({d}%)' 
                    }, 
                    labelLine :{show:true} 
                  } 
              } ,
            data:this.echartList
           }
          ]
         })
        },
         checkData(){
            this.HTTP.methods.apiGet("/login-logger/safe.shtml").then(res =>
            {
               if(res.data == false){
                    
                    this.$notify({
                      title: '警告',
                      message: '您访问的这张表数据不完整，记录被删除过'
                    });
               }

            }
        )
        },
        checkData(){
            this.HTTP.methods.apiGet("/opera-logger/safe.shtml").then(res =>
            {
               if(res.data == false){
                    
                    this.$notify({
                      title: '警告',
                      message: '您访问的这张表数据不完整，记录被删除过'
                    });
               }

            }
        )
        },
        download(){
            var param_s = encodeURI(JSON.stringify(this.exportCondition))
            let base = this.url
            let downloadUrl = "opera-logger/export.shtml?entity=" + param_s
            
            let data = {}
           
            var link = document.createElement('a')
            link.href = base + downloadUrl
            console.log(link.href)
            link.download = '操作日志导出表.xls'
            link.click()
           
        },
         reset() {
            this.reportPermission = false;
            this.form.result=null
            this.form.userId=null
            this.form.event=null
            this.form.source=null
            this.form.kernel=null
            this.form.normal=null
            this.form.stime=null
            this.form.etime=null
            this.form.module = null

            this.exportCondition.result=null
            this.exportCondition.userId=null
            this.exportCondition.event=null
            this.exportCondition.source=null
            this.exportCondition.kernel=null
            this.exportCondition.normal=null
            this.exportCondition.stime=null
            this.exportCondition.etime=null
            this.exportCondition.module = null
        },
         //每页显示数据量变更
        handleSizeChange: function(val) {
            this.pageSize = val;
            if(this.reportPermission){
                this.conditionQuery()
            }else{
                this.query()
            }
        },

        //页码变更
        handleCurrentChange: function(val) {
            this.pageNum = val;
            if(this.reportPermission){
                this.conditionQuery()
            }else{
                this.query()
            }
        },
        getSTime: function (val) {
            this.form.stime = val;
        },
        getETime: function (val) {
            this.form.etime = val;
        },
        refresh(){
            if(this.reportPermission){
                this.conditionQuery()
            }else{
                this.query()
            }

        },
        getPermissionNameById(pid){
            
           return this.pmap.get(pid)
        },
        initPermissionMap(){
            this.pmap = new Map()
            this.pmap.set("A0001","角色创建")
            this.pmap.set("A0002","角色查询")
            this.pmap.set("A0003","角色修改")
            this.pmap.set("A0004","角色删除")
            this.pmap.set("A0005","用户创建")
            this.pmap.set("A0006","用户查询")
            this.pmap.set("A0007","用户常规属性管理")
            this.pmap.set("A0008","用户删除")
            this.pmap.set("A0009","权限查询")
            this.pmap.set("A0010","权限修改")
            this.pmap.set("A0011","用户激活状态设置")
            this.pmap.set("A0012","用户锁定状态管理")
            this.pmap.set("A0013","用户绑定终端管理")
            this.pmap.set("A0014","用户激活状态查询")

            this.pmap.set("B0001","用户最大允许登录失败次数设定")
            this.pmap.set("B0002","终端最多允许登录失败次数设定")
            this.pmap.set("B0003","用户账号有效期设定")
            this.pmap.set("B0004","用户密码有效期设定")
            this.pmap.set("B0005","账户长期未使用期限设定")
            this.pmap.set("B0006","用户允许登录时间段设定")
            this.pmap.set("B0007","系统同时允许在线人数设定")
            this.pmap.set("B0008","用户高频登录设定")
            this.pmap.set("B0009","会话超时期限设定")
            this.pmap.set("B0010","终端锁定状态设定")

            this.pmap.set("C0001","驾驶人管理")
            this.pmap.set("C0002","机动车驾驶人关联")
            this.pmap.set("C0003","机动车交通违章查询确认")
            this.pmap.set("C0004","打印违章处罚决定书")

            this.pmap.set("D0001","用户登录日志查询")
            this.pmap.set("D0002","用户安全日志查询")
            this.pmap.set("D0003","用户操作日志查询")
            this.pmap.set("D0004","安全日志报表分析查询")
            this.pmap.set("D0005","操作日志报表分析查询")
            this.pmap.set("D0006","登录日志报表分析查询")
            this.pmap.set("D0007","登录日志存储期限设定")
            this.pmap.set("D0008","操作日志存储期限设定")
            this.pmap.set("D0009","安全日志存储期限设定")
            this.pmap.set("D0010","会话报文日志记录期限设定")

            this.pmap.set("X0000", "用户登陆")
            this.pmap.set("X0001", "修改自己账号密码")
        },
        timeFormatter: function (row, colum, cellValue) {
            return this.formatDateTime(row.time);
        },
        formatDateTime: function(inputTime){
            var date = new Date(inputTime);
            var y = date.getFullYear();
            var m = date.getMonth() + 1;
            m = m < 10 ? ('0' + m) : m;
            var d = date.getDate();
            d = d < 10 ? ('0' + d) : d;
            var h = date.getHours();
            h = h < 10 ? ('0' + h) : h;
            var minute = date.getMinutes();
            var second = date.getSeconds();
            minute = minute < 10 ? ('0' + minute) : minute;
            second = second < 10 ? ('0' + second) : second;
            return y + '-' + m + '-' + d+' '+h+':'+minute+':'+second;
        },
        tableRowClassName(row, rowIndex) {

            if (false == row.row.safe) {
                console.log(row.row)
                return { "background-color":"red"}
            }
            return '';
        },
        eventFormatter: function (row, column, cellValue) {
            
                return this.getPermissionNameById(row.event)
            
        },
        moduleFormatter : function (row, column, cellValue) {
            if(row.module.indexOf("A")>-1){
                return "系统管理"
            }else if(row.module.indexOf("B")>-1){
                return "安全管理";
            }else if(row.module.indexOf("C")>-1){
                return "业务管理"
            }else if(row.module.indexOf("D")>-1){
                return "审计管理"
            }else if(row.module.indexOf("X")>-1){
                return "基础权限"
            }
        },
        resultFormatter: function(row, column, cellValue){
            return 0 == row.result? "成功": "失败";
        },
    typeFormatter: function(row, column, cellValue) {
        switch (row.type){
            case 0:
                return "增加";
            case 1:
                return "删除";
            case 2:
                return "修改";
            case 3:
                return "查询";
        }
    },
    conditionQuery: function () {
         let msg = {
            result: this.form.result,
            event: this.form.event,
            source:this.form.source,
            userId: this.form.userId,
            module: this.form.module,
            stime: this.timeStrToTimestamp(this.form.stime),
            etime: this.timeStrToTimestamp(this.form.etime)
          }
          let url = "/opera-logger/findreport.shtml?pageSize="+this.pageSize+
                "&pageNum="+this.pageNum+"&entity="+encodeURI(JSON.stringify(msg));
            // let url = "/opera-logger/findreport.shtml?";
            // url = url+"pageSize="+this.pageSize+"&";
            // url = url+"pageNum="+this.pageNum+"&";
            // url = (this.form.result == null || this.form.result == '') ? url: url+"result="+this.form.result+"&";
            // url = (this.form.event == null || this.form.event == '') ? url: url+"event="+this.form.event+"&";
            // url = (this.form.source == null || this.form.source == '') ? url: url+"source="+this.form.source+"&";
            // url = (this.form.userId == null || this.form.userId == '') ? url: url+"userId="+this.form.userId+"&";
            //  url = (this.form.module == null || this.form.module == '') ? url: url+"module="+this.form.module+"&";
            // url = (this.form.stime == null || this.form.stime == '') ? url: url+"stime="+this.timeStrToTimestamp(this.form.stime)+"&";
            // url = (this.form.etime == null || this.form.etime == '') ? url: url+"etime="+this.timeStrToTimestamp(this.form.etime)+"&";
            // url = this.form.result == null ? url: url+"result="+this.form.result+"&";
            this.HTTP.methods.apiGet(url).then(res =>
            {
                //console.log(res)
                this.searchFlag = false;
            this.loading = true;
            if(null != res && 200 == res.code){

                this.tableData.body = res.data.list
                 this.totalCount = res.data.total
                this.loading = false
                this.reportPermission = true

                this.exportCondition.result=this.form.result
                this.exportCondition.userId=this.form.userId
                this.exportCondition.module=this.form.module
                this.exportCondition.source=this.form.source
                this.exportCondition.stime=this.form.stime
                this.exportCondition.etime=this.form.etime

                this.showReport()
                this.checkData()
            }else{
                this.tableData.body = []
                this.loading = false
                 this.totalCount =0 
                 this.reportPermission = false
            }
            }).catch(err => {
                    this.$message.error('网络超时')
                    this.loading = false
                     this.totalCount = 0
                      this.totalCount = []
                      this.reportPermission = false
                })
            },
        query(){
                this.HTTP.methods.apiGet("/opera-logger/page.shtml?pageSize="+this.pageSize+"&pageNum="+this.pageNum).then(res =>
                {
                    if(null != res && res.code == 200){
                        this.tableData.body = res.data.rows
                        this.totalCount = res.data.total
                        this.loading = false
                        this.showReport()
                        this.checkData()
                    }else{
                        this.tableData.body = []
                        this.loading = false
                        this.totalCount = 0
                    }
                }).catch(err => {
                    console.log(err)
                        this.$message.error('网络超时')
                        this.loading = false
                        this.totalCount = 0
                    })
        },
        timeStrToTimestamp: function (str) {
             if(str){
                str = str.substring(0,19);
                str = str.replace(/-/g,'/');
                return new Date(str).getTime();
            }
            return null;
        },
    },
    created() {
        this.query()
    }
}
</script>


